package com.ramos.kuaixiao.network;

import android.os.AsyncTask;
import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.SyncHttpClient;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.db.CustomerStoreDB;
import com.ramos.kuaixiao.db.SaleCustomerStoreDB;
import com.ramos.kuaixiao.entity.CustomerStore;
import com.ramos.kuaixiao.entity.SaleCustomerStore;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.FileUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class DownloadCustomerStoreTask extends AsyncTask<Void, Integer, Boolean> {
    private final static String TAG = "DownloadCustomerStore";
    private Set<String> customers = new HashSet<>();

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            //获取所有门店数据
            //getAllCustomerStore();
            getAllLocalSaleCustomerStore();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private void getAllLocalCustomerStore(Set<String> customers) {
        List<CustomerStore> tmplist = new ArrayList<>();
        File file = new File(FileUtil.getDataPath(App.mContext) + "/tbl_customer_store.csv");
        List<CustomerStore> list = readCustomerStoreCsv(file.getAbsolutePath());
        if (list != null && list.size() > 0) {
            CommUtil.d(App.mContext, TAG, "tbl_CustomerStore:" + list.size());
            CustomerStoreDB customerDB = new CustomerStoreDB();
            customerDB.addAllCustomer(list);
            /*if (customers != null && customers.size() > 0) {
                for (CustomerStore customer : list) {
                    for (String s : customers) {
                        if (customer.getCustomerId().equals(s)) {
                            tmplist.add(customer);
                        }
                    }
                }
                Log.d(TAG, "tbl_CustomerStore:" + list.size());
                CustomerStoreDB customerDB1 = new CustomerStoreDB();
                customerDB1.addAllCustomer(tmplist);
            }*/
        }
    }

    private void getAllLocalSaleCustomerStore() {
        File file = new File(FileUtil.getDataPath(App.mContext) + "/tbl_sale_customer_store.csv");
        List<SaleCustomerStore> list = readSaleCustomerStoreCsv(file.getAbsolutePath());
        if (list != null && list.size() > 0) {
            CommUtil.d(App.mContext,TAG, "tbl_SaleCustomerStore::" + list.size());
            SaleCustomerStoreDB customerDB = new SaleCustomerStoreDB();
            customerDB.addAllCustomer(list);
            /*for (SaleCustomerStore sale : list) {
                if (sale.getSale_id().equals(SharedPreference.getPreferString("id"))) {
                    customers.add(sale.getSale_id());
                }
            }*/
        }
        getAllLocalCustomerStore(customers);
    }

    public List<CustomerStore> readCustomerStoreCsv(String path) {
        List<CustomerStore> readerArr = new ArrayList<>();
        Scanner in = Utils.readCsv(path);
        try {
            in.nextLine();
            while (in.hasNextLine()) {
                String s = in.nextLine();
                String[] lines = s.split(",");
                /*if (Utils.replaceStr(lines[3]).equals(SharedPreference.getPreferString("dealer"))) {*/
                    CustomerStore bean = new CustomerStore(Utils.replaceStr(lines[0]), Utils.replaceStr(lines[2]), Utils.replaceStr(lines[4]), Utils.replaceStr(lines[3]),
                            Utils.replaceStr(lines[20]), Utils.replaceStr(lines[12]), Utils.replaceStr(lines[15]), Utils.replaceStr(lines[1]), Utils.replaceStr(lines[7]));
                    readerArr.add(bean);
                /*}*/
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return readerArr;
    }

    public List<SaleCustomerStore> readSaleCustomerStoreCsv(String path) {
        List<SaleCustomerStore> readerArr = new ArrayList<>();
        Scanner in = Utils.readCsv(path);
        try {
            in.nextLine();
            while (in.hasNextLine()) {
                String s = in.nextLine();
                String[] lines = s.split(",");
                if (Utils.replaceStr(lines[17]).equals("F")) {
                    SaleCustomerStore bean = new SaleCustomerStore(Utils.replaceStr(lines[1]), Utils.replaceStr(lines[1]),Utils.replaceStr(lines[1]),Utils.replaceStr(lines[5]), Utils.replaceStr(lines[3]), Long.valueOf(Utils.replaceStr(lines[4])));
                    readerArr.add(bean);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return readerArr;
    }


    @Override
    protected void onProgressUpdate(Integer... values) {

    }

    @Override
    protected void onPostExecute(Boolean result) {

    }

    private void getAllCustomerStore() {
        try {
            String url = NetUtils.CUSTOMER_STORE_ALL_LOCAL;
            String path = url + SharedPreference.getPreferString("dealer");
            Log.d(TAG, "CUSTOMER_STORE_ALL_LOCAL:path=" + path);
            SyncHttpClient client = new SyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(120000);
            client.get(path, new AsyncHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    //statusCode:状态码    headers：头信息  responseBody：返回的内容，返回的实体
                    //判断状态码
                    try {
                        String result = new String(responseBody, "utf-8");
                        JSONObject jsonObejct = JSONObject.parseObject(result);
                        Log.d(TAG, "CUSTOMER_STORE_ALL_LOCAL:result=" + result);
                        if (jsonObejct.getInteger("status") == 200) {
                            //JSONObject data = jsonObejct.getJSONObject("data");
                            List<CustomerStore> customerList = JSONArray.parseArray(jsonObejct.getJSONArray("data").toString(), CustomerStore.class);
                            if (customerList != null && customerList.size() > 0) {
                                Log.d(TAG, "CUSTOMER_STORE_ALL_LOCAL:mCustomerList=" + customerList.size());
                                CustomerStoreDB customerDB = new CustomerStoreDB();
                                customerDB.addAllCustomer(customerList);
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers,
                                      byte[] responseBody, Throwable error) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
